package com.zlx.guguanjia.mapper.provider;

import com.zlx.guguanjia.entity.SysArea;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.jdbc.SQL;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.Map;

/**
 * @Author 周罗校
 * @Description
 * @ClassName SysAreaSqlProvider
 * @date 2020.10.30 12:37:39
 * 该版权归周罗校所有，最终解释权以官方为准
 */
public class SysAreaSqlProvider {
    public String selectPage(Map<String,Object> map){
        return new SQL(){{
            SELECT("sub.*,parent.`name` parent_name");
            FROM("sys_area sub");
            LEFT_OUTER_JOIN("sys_area parent " +
                    "ON sub.parent_id = parent.id");
            WHERE("sub.del_flag = '0'");
            if (map.containsKey("sid")&&!StringUtils.isEmpty(map.get("sid"))){
                WHERE("FIND_IN_SET(#{sid},sub.parent_ids) or sub.id = #{sid}");
            }else if (map.containsKey("name")&&!StringUtils.isEmpty(map.get("name"))){
                WHERE("sub.`name` LIKE CONCAT('%',#{name},'%')");
            }
        }
        }.toString();
    }

    public String insertBitch(@Param("areas") List<SysArea> areas){
        return new SQL(){{
            INSERT_INTO("`sys_area`");
            INTO_COLUMNS("`id`, `parent_id`, `parent_ids`, `code`, `name`, `type`, `create_by`, `create_date`, `update_by`, `update_date`, `remarks`, `del_flag`, `icon`");
            for (int i = 0; i < areas.size(); i++) {
                StringBuilder sb = new StringBuilder();
                if (i!=0){
                    sb.append("(");
                }
                sb.append("null,#{areas[").append(i).append("].parentId},#{areas[").append(i).
                        append("].parentIds},#{areas[").append(i).append("].code},#{areas[").append(i).
                        append("].name},#{areas[").append(i).append("].type},#{areas[").append(i).
                        append("].createBy},NOW(),#{areas[").append(i).
                        append("].updateBy},NOW(),#{areas[").append(i).
                        append("].remarks},#{areas[").append(i). append("].delFlag},#{areas[").append(i).
                        append("].icon}");
                if (i!=areas.size()-1){
                    sb.append(")");
                }
                INTO_VALUES(sb.toString());
                INTO_VALUES();
            }
        }
        }.toString();
    }
}
